<template>
    <div>
        <div class="customer-tools">
            <h3>经营单位</h3>
            <Button type="primary" :disabled="disabled" @click="operatingData(addBusiness)">新增</Button>
        </div>

        <Table
            id="business_table"
            ref="businessTable"
            :data="businessData"
            :columns="businessColumns"
            @on-row-dblclick="onRowDblclick"
        >
            <!-- 经营单位名称 -->
            <template slot="unitName" slot-scope="props">
                <Input v-if="props.isEdit" v-model="props.unitName"></Input>
                <span v-else>{{props.unitName}}</span>
            </template>
            <!-- 经营单位海关代码 -->
            <template slot="unitCustomsCode" slot-scope="props">
                <Input v-if="props.isEdit" v-model="props.unitCustomsCode"></Input>
                <span v-else>{{props.unitCustomsCode}}</span>
            </template>
            <!-- 统一社会信用代码 -->
            <template slot="unitCreditCode" slot-scope="props">
                <Input v-if="props.isEdit" v-model="props.unitCreditCode"></Input>
                <span v-else>{{props.unitCreditCode}}</span>
            </template>
            <!-- 检验检疫代码 -->
            <template slot="unitCiqCode" slot-scope="props">
                <Input v-if="props.isEdit" v-model="props.unitCiqCode" @on-enter="saveBusiness(props._index)"></Input>
                <span v-else>{{props.unitCiqCode}}</span>
            </template>
            <!-- 电子签章 -->
            <template slot="qzUrl" slot-scope="props">
                <i
                    v-if="!disabled || props.qzUrl"
                    :class="['table-icon', props.qzUrl ? 't-view-icon' : 't-upload-icon'] "
                    :title="props.qzUrl ? '查看' : '上传'"
                    @click.stop="openImgModal(props.qzUrl, props._index)"
                >
                </i>
            </template>
            <!-- 管理 -->
            <template slot="action" slot-scope="props">
                <div class="table-action">
                    <template v-if="props.isEdit">
                        <i class="table-icon t-save-icon" title="保存" @click.stop="saveBusiness(props._index)"></i>
                        <i class="table-icon t-cancel-icon" title="取消" @click.stop="cancelBusiness(props._index)"></i>
                    </template>
                    <template v-else>
                        <i class="table-icon t-edit-icon" title="编辑" @click.stop="operatingData(editBusiness, props._index)"></i>
                        <i class="table-icon t-del-icon" title="删除" @click.stop="operatingData(deleteBusiness, props._index)"></i>
                    </template>
                </div>
            </template>
        </Table>
        <!-- 电子签章 -->
        <SignatureModal
            v-model="imgModal.visible"
            :url="imgModal.url"
            :disabled="disabled"
            @deleted="delModalImg"
            @upload="handleSuccess"
        ></SignatureModal>
    </div>
</template>
<script>
import { focusIndexInput, nextFocus } from '@/libs/ivuDom'
import { on } from '@/libs/tools'
import { validateSocialCreditCode } from '@/libs/validate'
import businessColumns from '../js/businessColumns'
import SignatureModal from './signature-modal'
export default {
    components: {
        SignatureModal
    },
    props: {
        disabled: {
            type: Boolean,
            default: false
        }
    },
    data () {
        let columns = businessColumns(this)
        return {
            businessData: [],
            businessColumns: columns,
            imgModal: {
                // 电子签章预览弹出层
                visible: false,
                url: '',
                index: ''
            }
        }
    },
    created () {
        if (this.disabled) {
            this.businessColumns.pop()
        }
    },
    mounted () {
        this.temporaryData = null // 暂存编辑前的数据（0代表新增的数据）
        this.$nextTick(_ => {
            this.bindInputsEnterEvent()
        })
    },
    methods: {
        // 查找需要绑定回车事件的input
        findInputs () {
            this.$nextTick(_ => {
                this.inputs = document.querySelectorAll('#business_table .ivu-table-body input[type=text]')
                setTimeout(_ => {
                    focusIndexInput(0, this.inputs)
                }, 50)
            })
        },
        // 绑定input回车事件
        bindInputsEnterEvent () {
            const self = this
            on(document.querySelector('#business_table .ivu-table-body'), 'keyup', function next (event) {
                if (event.keyCode === 13) {
                    nextFocus(event, self.inputs)
                }
            })
        },
        // 新增经营单位
        addBusiness () {
            this.businessData.push({
                unitId: '',
                unitName: '',
                unitCustomsCode: '',
                unitCreditCode: '',
                unitCiqCode: '',
                qzUrl: '',
                isEdit: true
            })
            this.temporaryData = 0
            this.findInputs()
        },
        // 编辑经营单位
        editBusiness (index) {
            this.temporaryData = JSON.stringify(this.businessData[index])
            this.businessData[index].isEdit = true
            this.findInputs()
        },
        // 删除经营单位
        deleteBusiness (index) {
            this.businessData.splice(index, 1)
        },
        // 保存经营单位
        saveBusiness (index) {
            if (this.checkData(index)) {
                this.businessData[index].isEdit = false
                this.temporaryData = null
            }
        },
        // 取消
        cancelBusiness (index) {
            if (this.temporaryData) {
                const data = JSON.parse(this.temporaryData)
                let item = this.businessData[index]
                Object.keys(data).forEach(key => {
                    item[key] = data[key]
                })
            } else if (this.temporaryData === 0) {
                this.businessData.pop()
            }
            this.temporaryData = null
        },
        // 双击编辑
        onRowDblclick (item, index) {
            if (this.businessData[index].isEdit) return
            this.operatingData(this.editBusiness, index)
        },
        checkData (index) {
            const data = this.businessData[index]
            let errs = []
            const codeReg = /^(\d|[A-Z]){10}$/
            if (!data.unitName) {
                errs.push('请输入经营单位名称')
            } else if (data.unitName.length > 60) {
                errs.push('经营单位名称60个字符内')
            }
            if (!data.unitCustomsCode) {
                errs.push('请输入经营单位海关代码')
            } else if (!codeReg.test(data.unitCustomsCode)) {
                errs.push('经营单位海关代码大写英文字母或数字，长度等于10')
            }
            if (!data.unitCreditCode) {
                errs.push('请输入统一社会信用代码')
            } else if (!validateSocialCreditCode(data.unitCreditCode)) {
                errs.push('统一社会信用代码大写英文字母或数字，长度等于18')
            }
            if (data.unitCiqCode && !codeReg.test(data.unitCiqCode)) {
                errs.push('检验检疫代码大写英文字母或数字，长度等于10')
            }
            if (errs.length) {
                this.$Modal.warning({
                    title: '请检查数据格式',
                    content: errs.join('<br>')
                })
                return false
            }
            return true
        },
        /**
         * 操作数据  执行一些操作前先判断是否存在编辑的数据
         * fn Function 需要执行的函数
         * arg 需要传入fn的参数
         */
        operatingData (fn, ...arg) {
            if (this.temporaryData === null) {
                fn && fn(...arg)
            } else {
                this.$Message.warning('请先保存正在编辑的经营单位')
            }
        },
        // 打开签章弹窗
        openImgModal (url, index) {
            this.imgModal.visible = true
            this.imgModal.index = index
            this.imgModal.url = url
        },
        // 删除图片
        delModalImg () {
            this.businessData[this.imgModal.index].qzUrl = ''
            this.imgModal.url = ''
        },
        // 上传成功
        handleSuccess (url) {
            this.imgModal.url = url
            this.businessData[this.imgModal.index].qzUrl = url
        },
        // 校验
        validate (fn) {
            const result = this.temporaryData === null
            fn && fn(result)
            return new Promise((resolve, reject) => {
                resolve(result)
            })
        },
        // 获取数据
        getData () {
            return this.businessData.map(item => {
                return {
                    unitId: item.unitId,
                    unitName: item.unitName,
                    unitCustomsCode: item.unitCustomsCode,
                    unitCreditCode: item.unitCreditCode,
                    unitCiqCode: item.unitCiqCode,
                    qzUrl: item.qzUrl
                }
            })
        },
        setData (list) {
            this.temporaryData = null
            this.businessData = list.map(item => {
                return {
                    unitId: item.unitId,
                    unitName: item.unitName,
                    unitCustomsCode: item.unitCustomsCode,
                    unitCreditCode: item.unitCreditCode,
                    unitCiqCode: item.unitCiqCode,
                    qzUrl: item.qzUrl,
                    isEdit: false
                }
            })
        }
    }
}
</script>
<style lang="less" scoped>
@import "../less/customer.less";
</style>
